/* eslint-disable require-atomic-updates */
/* eslint-disable no-param-reassign */
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Box, Button, Dialog, Drawer, Icon, Message, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { useHistory, useParams } from 'react-router';
import CompanyRouteForm from './components/CompanyRouteForm';
import CompanyRouteFormLand from './components/CompanyRouteFormLand';
import { column, ENUMS } from './stores/definitions';
import ScAddLineForm from './components/ScAddLineForm';

const ROUTE_TYPES = {
  1: 'editLand',
  2: 'edit',
  undefined: 'editSc',
};

const tabItems = [
  { key: '0', label: '包车跨境线路' },
  { key: '1', label: '包车内地线路' },
  { key: '2', label: '专线线路' },
];

function CompanyRoute() {
  const history = useHistory();
  const { companyId } = useParams();
  const [modal, setModal] = useState([]);
  const { companyRouteStore: store, companyStore } = useStore();
  const objRef = useRef(); // current
  const [dup, setDup] = useState([]);

  useEffect(() => {
    store.search = { companyIds: [companyId] };
    (async () => {
      await store.fetchGroups();
      await store.getCompany({ search: { }, pg: { size: 999 } });
    })();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { startArea: _, endArea: __, priceCopy, ...searchArgs } = params.values;
    if (priceCopy) {
      Dialog.confirm({
        content: t`是否复制【${priceCopy}公司】的【${ENUMS._typeText[store._priceStatus]}线路】`,
        onOk: () => currentCopyPrice(priceCopy),
      });
      return;
    }
    const { startArea, endArea } = params.valueObjects;
    store.search = {
      companyIds: [companyId],
      startMainArea: startArea?.selectedPath?.[0]?.value,
      startMinorAreas: startArea?.selectedPath?.length > 1 ? [startArea?.selectedPath?.[1].itemId] : [],
      endMainArea: endArea?.selectedPath?.[0]?.value,
      endMinorAreas: endArea?.selectedPath?.length > 1 ? [endArea?.selectedPath?.[1].itemId] : [],
      ...searchArgs,
    };
  };

  /**
     * @description 确认拷贝线路逻辑
     * @param {String} v
     */
  async function currentCopyPrice(v) {
    if (v === '【平台线路】') {
      v = '';
    }
    try {
      const args = {
        originalCompany: v,
        targetCompany: companyId,
        type: store._priceStatus === '0' ? '2' : '1',
        priceType: store._priceStatus === '2' ? 2 : 1,
      };
      await store.cbvCompanyPriceCopy({ ...args });
    } catch (error) {
      console.log('🚀 _ file: index.jsx:83 _ error:', error);
      throw error;
    }
  }

  // 点击打开添加
  const handleOpenAdd = (type) => {
    objRef.current = {};
    setModal([type]);
  };

  // 点击打开编辑
  const handleOpenEdit = (current) => {
    objRef.current = current;
    setModal([ROUTE_TYPES[current.type]]);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      const exists = await store.exitingLines(result);
      if (exists.length > 0 && exists[0].startMain) {
        setDup(exists);
        return;
      }
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      const companyInfo = await companyStore.get(companyId);
      result.companyId = companyId;
      result.companyName = companyInfo.name;
      const exists = await store.exitingLines(result);
      if (exists.length > 0 && exists[0].startMain) {
        setDup(exists);
        return;
      }

      try {
        await store.create(toJS(result));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 数据删除
  const handleDelete = (price) => {
    Dialog.confirm({
      content: t`确认删除该线路吗？`,
      onOk: async () => {
        try {
          await store.remove(toJS(price));
          Message.success({ content: t`删除成功` });
        } catch (e) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw e;
        }
      },
    });
  };

  return (
    <TauPage className="page-container">
      <Box direction="row" align="center" margin={10}>
        <Button type="normal" onClick={() => { history.goBack(); }} style={{ marginLeft: '-10px', border: 0 }}>
          <Icon type="arrow-left" style={{ padding: 6, border: '1px solid #ccc', borderRadius: '50%', color: 'var(--btn-pure-primary-bg)' }} />
        </Button>
        <div>{t`承运商【${store.company.find((p) => p.value === companyId)?.label}】的线路信息`}</div>
      </Box>
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-addCompanyPrice',
            title: t`添加跨境线路`,
            type: 'primary',
            onClick: () => handleOpenAdd('add'),
          },
          {
            name: 'btn-addCompanyLandPrice',
            title: t`添加内地线路`,
            type: 'primary',
            onClick: () => handleOpenAdd('addLand'),
          },
          {
            name: 'btn-addScLine',
            title: t`添加专线线路`,
            type: 'primary',
            onClick: () => handleOpenAdd('addSc'),
          },
        ]}
        searchItems={[
          {
            name: 'startArea',
            type: 'cc-station',
            props: {
              placeholder: t`始发城市/区域`,
              changeOnSelect: true,
              maxLevel: 2,
            },
          },
          {
            name: 'endArea',
            type: 'cc-station',
            props: {
              placeholder: t`到达城市/区域`,
              changeOnSelect: true,
              maxLevel: 2,
            },
          },
          {
            name: 'priceCopy',
            type: 'select',
            props: {
              dataSource: store.company,
              placeholder: t`线路拷贝`,
              style: { width: '200px' },
              // onChange: handlePriceCopy,
            },
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <Tab
        activeKey={store.priceStatus}
        onChange={(v) => { store.priceStatus = v; }}
      >
        {tabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
      </Tab>
      <div className="content">
        <TauTable
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.prices)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column(store.priceStatus === '2' ? 'scBeginAreaName' : 'beginAreaName', { width: 128 }),
            column(store.priceStatus === '2' ? 'scEndAreaName' : 'endAreaName', { width: 128 }),
            column('specificSingleFare.RMB', { width: 180 }),
            column('state', { width: 88 }),
            {
              title: t`操作`,
              dataIndex: 'id',
              width: 100,
              cell: (_, __, price) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(price)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDelete(price)} >{t`删除`}</Button>
                </>),
            },

          ]}
        />
      </div>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit'}
        title={modal[0] === 'add' ? t`添加跨境线路` : t`修改跨境线路`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width={modal[0] === 'add' ? '700px' : '90%'}
      >
        <CompanyRouteForm
          priceId={objRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'addLand' || modal[0] === 'editLand'}
        title={modal[0] === 'addLand' ? t`添加内地线路` : t`修改内地线路`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width={modal[0] === 'addLand' ? '700px' : '90%'}
      >
        <CompanyRouteFormLand
          priceId={objRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'addLand' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'addSc' || modal[0] === 'editSc'}
        title={modal[0] === 'addSc' ? t`添加专线线路` : t`修改专线线路`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width={modal[0] === 'addSc' ? '700px' : '90%'}
      >
        <ScAddLineForm
          priceId={objRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'addSc' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Dialog
        v2
        title={t`存在重复的线路`}
        centered
        width="50%"
        height="70vh"
        onOk={() => setDup([])}
        onClose={() => setDup([])}
        visible={dup.length}
        footerActions={['ok']}
      >
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
          {dup.map((v) => <span>{`${v.startMainText}-${v.startMinorText} ---> ${v.endMainText}-${v.endMinorText}`}</span>)}
        </div>
      </Dialog>
    </TauPage>
  );
}

export default observer(CompanyRoute);
